package com.acenodie.acenodieopenglturorial.filter;

import java.nio.FloatBuffer;

import android.opengl.GLES20;



public class OutputFilter extends GPUImageFilter {
	private static final String TAG = "SPOutputFilter";

	
	public static final String OUTPUT_VERTEX_SHADER = "" 
			+ "attribute vec4 position;\n"
			+ "attribute vec4 inputTextureCoordinate;\n" 
			+ " \n" + "varying vec2 textureCoordinate;\n" 
			+ " \n"
			+ "void main()\n" + "{\n" 
			+ "    gl_Position = position;\n"
			+ "    textureCoordinate = inputTextureCoordinate.xy;\n" 
			+ "}";
	
	private static final String OUTPUT_FRAGMENT_SHADER = "" 
			+ "varying highp vec2 textureCoordinate;\n" 
			+ "uniform sampler2D inputImageTexture;\n" + "\n"
			+ "void main()\n" + "{\n" 
			+ "gl_FragColor = texture2D(inputImageTexture, textureCoordinate);\n"
			+ "}";
	
	public OutputFilter() {
		super(OUTPUT_VERTEX_SHADER, OUTPUT_FRAGMENT_SHADER);
	}
	
	protected void onInit() {
		super.onInit();
	}
	
	protected void onDestroy() {
		super.onDestroy();
	}
	
	@Override
	public int onDrawFrame(int textureId, FloatBuffer vertexBuffer, FloatBuffer textureBuffer) {
		GLES20.glViewport(0, 0, mSurfaceWidth, mSurfaceHeight);
		GLES20.glUseProgram(mGLProgId);
		runPendingOnDrawTasks();
		if (!isInitialized()) {
			return OpenGLUtils.NOT_INIT;
		}
		vertexBuffer.position(0);
		GLES20.glVertexAttribPointer(mGLAttribPosition, 2, GLES20.GL_FLOAT, false, 0, vertexBuffer);
		GLES20.glEnableVertexAttribArray(mGLAttribPosition);
		textureBuffer.position(0);
		GLES20.glVertexAttribPointer(mGLAttribTextureCoordinate, 2, GLES20.GL_FLOAT, false, 0,
				textureBuffer);
		GLES20.glEnableVertexAttribArray(mGLAttribTextureCoordinate);

		if (textureId != OpenGLUtils.NO_TEXTURE) {
			GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
			GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
			GLES20.glUniform1i(mGLUniformTexture, 0);
		}

		GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
		GLES20.glDisableVertexAttribArray(mGLAttribPosition);
		GLES20.glDisableVertexAttribArray(mGLAttribTextureCoordinate);
		GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
		return OpenGLUtils.ON_DRAWN;
	}

}
